// compnents/goodsCountModal/goodsCountModal.js
const app = getApp()
import { goodsDateils, addToCart } from '../../api/url.js'
import { formatSku } from '../../utils/util.js'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    goodsId: {//商品id
      type: String,
      value: ''
    },
    fromPage: {//从哪个页面打开
      type: String,
      value: 'goodsDetail'
    },
    indexCount: {//如果从首页打开，传入商品数量
      type: Number,
      value: 0
    },
    isIPX: {//是否是iPhoneX
      type:Boolean,
      value:false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    count: 1,
    detail: {},//商品详情
  },
  
  /**
   * 组件的方法列表
   */
  methods: {
    //关闭模态框
    close() {
      this.triggerEvent('closeModal')
    },
    //设置剩余库存
    setStock() {
      let that = this
      let temDetail = that.data.detail
      let skuId = that.getFProductRuleId()
      if(skuId!==0){
        temDetail.fTotalCount = temDetail.skuAndPropAndPropValList.filter(val => val.fId === skuId)[0].fStock
      }
      that.setData({
        detail:temDetail
      })
    },
    //选择sku
    selectSku(e) {
      let that = this
      let option = e.currentTarget.dataset.option
      let temDetail = that.properties.detail
      let name = e.currentTarget.dataset.name
      temDetail.skuData.skuList.forEach(val => {
        if (val.name === name) {
          val.options.forEach(val1 => {
            val1.selected = false
            if (val1.name === option.name) {
              val1.selected = true
            }
          })
        }
      })
      that.setData({
        detail: temDetail
      })
      that.setSkuPri()
      that.setStock()
    },
    //获取skuid
    getFProductRuleId() {
      let that = this
      if (that.properties.detail.skuAndPropAndPropValList && that.properties.detail.skuAndPropAndPropValList.length > 0) {
        let selected = that.properties.detail.skuData.skuList.map(val => {
          return val.options.filter(val2 => val2.selected)[0]
        })
        let selectedStr = selected.map(val => val.name).join('')
        let temSku = that.properties.detail.skuData.priceMap.filter(val => {
          let temStr = val.map.join('')
          return selectedStr === temStr
        })
        return temSku[0].id
      } else {
        return 0
      }

    },
    //设置数量
    setCount(e) {
      let that = this
      let type = e.currentTarget.dataset.type
      switch (type) {
        case 'minus':
          if (that.data.count > 1) {
            that.setData({
              count: that.data.count - 1
            })
          }
          that.setSkuPri()
          break
        case 'plus':
          let total = e.currentTarget.dataset.total
          if (that.data.count < total) {
            that.setData({
              count: that.data.count + 1
            })
          }
          that.setSkuPri()
          break
        case 'input':
          total = e.currentTarget.dataset.total
          if (Number(e.detail.value) <= total && Number(e.detail.value) >= 1) {
            that.setData({
              count: Math.floor(Number(e.detail.value))
            })
            that.setSkuPri()
          } else {
            wx.showToast({
              title: '数量有误',
              icon: 'none'
            })
            if (Number(e.detail.value) <= 1) {
              that.setData({
                count: 1
              })
            } else if (Number(e.detail.value) > total) {
              that.setData({
                count: total
              })
            } else {
              that.setData({
                count: that.data.count
              })
            }
            that.setSkuPri()
          }
          break
      }
    },
    //设置skuPriTxt
    setSkuPri() {
      let that = this
      let skuId = that.getFProductRuleId()
      let temDetail = that.properties.detail
      if (that.data.detail.skuData) {
        let skuPri = Number(temDetail.skuData.priceMap.filter(val => {
          return val.id === skuId
        })[0].price)
        temDetail.skuPriTxt = (skuPri * that.data.count).toFixed(2)
        that.setData({
          detail: temDetail
        })
      } else {
        temDetail.skuPriTxt = (temDetail.fFixedPrice * that.data.count).toFixed(2)
        that.setData({
          detail: temDetail
        })
      }

    },
    //加载商品详情
    loadGoodsDetail(id) {
      let that = this
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      wx.request({
        url: goodsDateils,
        data: {
          id
        },
        success(res) {
          wx.hideLoading()
          if (res.data.code === 0) {
            let temDetail = res.data.response.cont
            temDetail.productImgList.forEach(val => {
              val.img = app.globalData.imageBaseUrl + val.fImage
            })
            temDetail.priceTxt = temDetail.fFixedPrice.toFixed(2)
            if (temDetail.skuAndPropAndPropValList && temDetail.skuAndPropAndPropValList.length > 0) {
              temDetail.skuData = formatSku(temDetail.skuAndPropAndPropValList, that.data.goodsId)
              temDetail.fTotalCount = temDetail.skuAndPropAndPropValList[0].fStock
            } else {
              temDetail.skuData = null
            }
            if (temDetail.skuData) {
              temDetail.skuPriTxt = temDetail.skuData.priceMap[0].price
            } else {
              temDetail.skuPriTxt = temDetail.priceTxt
            }
            that.setData({
              detail: temDetail
            })
            that.setSkuPri()
          } else {
            wx.showToast({
              title: '加载商品详情异常',
              icon: 'none'
            })
          }
        },
        fail() {
          wx.hideLoading()
          wx.showToast({
            title: '加载商品失败',
            icon: 'none'
          })
        }
      })
    },
    //加入购物车
    addCart() {
      let that = this
      let query
      if (that.getFProductRuleId() === 0) {
        query = {
          fUserId: app.globalData.userInfo.id,
          fProductId: that.data.goodsId,
          fToken: 1,
          fCount: that.data.count,
          fState: 1,
          fType: 0,
          loginName: app.globalData.userInfo.loginname,
          token: wx.getStorageSync('token')
        }
      } else {
        query = {
          fUserId: app.globalData.userInfo.id,
          fProductId: that.data.goodsId,
          fProductRuleId: that.getFProductRuleId(),
          fToken: 1,
          fCount: that.data.count,
          fState: 1,
          fType: 0,
          loginName: app.globalData.userInfo.loginname,
          token: wx.getStorageSync('token')
        }
      }
      let temStock
      let skuId = that.getFProductRuleId()
      if(skuId!=0){
        temStock = that.data.detail.skuAndPropAndPropValList.map(val => {
          if (val.fId === skuId) {
            return val.fStock
          }
        }).filter(val => val)[0]
      }else{
        temStock = that.data.detail.fTotalCount
      }
      
      if (temStock > 0) {
        wx.request({
          url: addToCart,
          data: query,
          success(res) {
            if (res.data.code === 0) {
              wx.showToast({
                title: '加入购物车成功',
                icon: 'success'
              })
              that.triggerEvent('closeModal')
            } else {
              wx.showToast({
                title: '加入购物车失败',
                icon: 'none'
              })
            }
          }
        })

      } else {
        wx.showToast({
          title: '库存不足',
          icon: 'none'
        })
      }
    },
    //立即购买
    buyNow() {
      let that = this
      if (app.globalData.userInfo && app.globalData.wxUserInfo) {
        const skuInfo = `${that.data.detail.fId}:${that.getFProductRuleId()}:${that.data.count}`
        let skuId = that.getFProductRuleId()
        if (skuId == 0) {
          wx.navigateTo({
            url: `/pages/confirmOrder/confirmOrder?data=${skuInfo}`
          })
        } else {
          let temStock = that.data.detail.skuAndPropAndPropValList.map(val => {
            if (val.fId === skuId) {
              return val.fStock
            }
          }).filter(val => val)[0]
          if (temStock > 0) {
            wx.navigateTo({
              url: `/pages/confirmOrder/confirmOrder?data=${skuInfo}`
            })
          } else {
            wx.showToast({
              title: '库存不足',
              icon: 'none'
            })
          }
        }

      } else {
        wx.showToast({
          title: '请授权',
          icon: 'none'
        })
      }
    },
  },

  ready() {
    let that = this
    switch (that.properties.fromPage) {
      case 'goodsDetail':
        that.loadGoodsDetail(that.properties.goodsId)
        break
      case 'index':
        that.setData({
          count: that.properties.indexCount
        })
        that.loadGoodsDetail(that.properties.goodsId)
        break
    }

  }
})